const std = @import("std");
const builtin = @import("builtin");
const icelib = @import("icelib/icelib.zig");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    try main_run(allocator);
}

fn main_run(allocator: std.mem.Allocator) !void {
    // 指定windows的命令行使用utf-8编码
    if (builtin.os.tag == std.Target.Os.Tag.windows) {
        _ = std.os.windows.kernel32.SetConsoleOutputCP(65001);
    }

    try icelib.setThreadName("mainThread");
    const log_config = icelib.LogConfig.init(allocator, "log/learn.txt");
    try icelib.Logger.init(log_config);
    defer icelib.Logger.getInstance().deinit();

    try icelib.log.info(@src(), "日志功能加载完成", .{});

    // 监听地址和端口
    const port: u16 = 5505;
    const address = try std.net.Address.parseIp4("127.0.0.1", port);
    var server = try std.net.Address.listen(address, .{ .reuse_address = true });

    try icelib.log.info(@src(), "HTTP服务器启动成功: http://127.0.0.1:{d}", .{port});
    var buff = icelib.String.init(allocator);
    defer buff.deinit();
    try buff.setNeedSize(65535);
    while (true) {
        const conn = try server.accept();
        defer conn.stream.close();
        const temp = try buff.data();
        var client = std.http.Server.init(conn, temp);

        var request = std.http.Server.receiveHead(&client) catch |err| {
            switch (err) {
                std.http.Server.ReceiveHeadError.HttpConnectionClosing => break,
                else => return err,
            }
        };
        buff.updateUseSize();

        const data = try icelib.Request.init(allocator, buff);
        defer data.deinit();
        const method = try data.toStr();
        defer method.deinit();

        std.debug.print("{s}\n", .{method.toStr()});
        if (data.method == .GET) {
            var root_path = icelib.String.init(allocator);
            try root_path.setNeedSize(100);
            try root_path.pushBackCharArray("D:/project/zig/zigframe/html");
            defer root_path.deinit();

            var full_path = try root_path.clone();
            defer full_path.deinit();
            try full_path.pushBackStr(data.uri);
            if (data.uri.equal("/")) {
                try request.respond("404 Not Found\n", .{
                    .status = .moved_permanently,
                    .extra_headers = &.{
                        .{ .name = "Location", .value = "/index.html" },
                    },
                });
                // try full_path.pushBackCharArray("index.html");
                // try icelib.serveStaticFile(&request, full_path.toStr());
            } else if (data.uri.equal("/vite.svg") or data.uri.equal("/index.html")) {
                try icelib.serveStaticFile(&request, full_path.toStr());
            } else if (data.uri.startWith("/assets/")) {
                try icelib.serveStaticFile(&request, full_path.toStr());
            }
        }
        try request.respond("Hello http.std!", .{});
    }
}

test "simple test" {
    try main_run(std.testing.allocator);
}
